package org.shop.controller.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Goods;
import org.shop.entity.Merchant;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.MerchantService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class WebMerchantController {
	
	private static Logger logger = LogManager.getLogger(WebMerchantController.class);
	
	@Autowired
	private MerchantService merchantService;
	@Autowired
    private UserService userService;
	
	
	/**
	 * 申请店铺
	 * @param req
	 * @return
	 */
	@RequestMapping("web/shopApply")
	@ResponseBody
	public Map<String, Object> shopApply(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
    	String certificatePhotoStr="";
    	String businessPhotoStr="";
		FTPClient ftpClient =null;
		try{
			MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Users users=userService.selectByPrimaryKey(ud.getUserId());
			if(users.getMerchantId()!=null){
				map.put("state", 2);
    			map.put("msg", "店铺已申请");
    			return map;
			}
			
    		//创建一个通用的多部分解析器
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
    		//转换成多部分request  
    		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			
    			String merchantName = multiRequest.getParameter("merchantName");
    			Map<String, Object> paramMap=new HashMap<String, Object>();
    			paramMap.put("merchantName", merchantName);
    			int count=merchantService.verifyMerchantName(paramMap);
        		if(count>0){
        			map.put("state", 2);
        			map.put("msg", "店铺名称已经存在");
        			return map;
        		}
    			
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/apply/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
    				//取得上传文件
    				List<MultipartFile> fileList = multiRequest.getFiles(name);
    				if(fileList!=null){
    					for(MultipartFile file:fileList){
    						if(file != null){
    							//取得当前上传文件的文件名称
    	    					String myFileName = file.getOriginalFilename();
    	    					myFileName=FtpUtil2.generateFileName(myFileName);
    	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
    	    					if(myFileName.trim() !=""){
    	    						myFileName=FtpUtil2.generateFileName(myFileName);
    	    						InputStream is = file.getInputStream();
    	    						FtpUtil2.upload(myFileName, is, ftpClient);
    	    						if(name.equals("certificatePhoto")){
    	    							certificatePhotoStr+=ftp_photoDirectory+"/"+myFileName;
    	    						}else if(name.equals("businessPhoto")){
    	    							businessPhotoStr+=ftp_photoDirectory+"/"+myFileName;
    	    						}
    	    					}
    						}
    					}
    				}
    			}
    			String merchartClassifyId = multiRequest.getParameter("merchartClassifyId");
    			String merchantAddress = multiRequest.getParameter("merchantAddress");
    			String merchartIntro = multiRequest.getParameter("merchartIntro");
    			String userName = multiRequest.getParameter("userName");
    			String idNo = multiRequest.getParameter("idNo");
    			Merchant merchant = new Merchant();
    			merchant.setMerchantName(merchantName);
    			merchant.setMerchartClassifyId(Long.parseLong(merchartClassifyId));
    			merchant.setMerchantAddress(merchantAddress);
    			merchant.setMerchartIntro(merchartIntro);
    			merchant.setSchoolId(ud.getSchoolId());
    			merchant.setHandIdcardImg(certificatePhotoStr);
    			merchant.setHardBusinessLicenseImg(businessPhotoStr);    
    			merchant.setState((byte)1);
    			merchantService.insertSelective(merchant);
    			users.setUserId(ud.getUserId());
    			users.setRealName(userName);
    			users.setIdNo(idNo);
    			users.setMerchantId(merchant.getMerchantId());
    			userService.updateByPrimaryKeySelective(users);
    			map.put("state", 1);
    			map.put("msg", "申请成功");
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "申请失败");
    	}finally {
    		try {
				if(ftpClient!=null){
					FtpUtil2.closeConnection(ftpClient);
				}
			} catch (Exception e) {
				ftpClient=null;
			} 
		}
		return map;
	}
	
	/**
	 * 获取店铺信息
	 * @param req
	 * @return
	 */
	@RequestMapping("web/getShopInfo")
	@ResponseBody
	public Map<String, Object> getShopInfo(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Merchant merchant=merchantService.selectByPrimaryKey(ud.getMerchantId());
			map.put("merchant", merchant);
			map.put("realName", ud.getRealName());
			map.put("idNo", ud.getIdNo());
			return map;
		} catch(Exception e) {
			logger.error(e);
		}
		return null;
	}
	
	/**
	 * 店铺再次申请
	 * @param req
	 * @return
	 */
	@RequestMapping("web/shopReapply")
	@ResponseBody
	public Map<String, Object> shopReapply(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
    	String certificatePhotoStr="";
    	String businessPhotoStr="";
		FTPClient ftpClient =null;
		try{
			MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    		//创建一个通用的多部分解析器
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
    		//转换成多部分request  
    		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			Merchant merchant = new Merchant();
    			merchant.setMerchantId(ud.getMerchantId());
    			String merchantName = multiRequest.getParameter("merchantName");
    			Map<String, Object> paramMap=new HashMap<String, Object>();
    			paramMap.put("merchantName", merchantName);
    			paramMap.put("merchantId", ud.getMerchantId());
    			int count=merchantService.verifyMerchantName(paramMap);
        		if(count>0){
        			map.put("state", 2);
        			map.put("msg", "店铺名称已经存在");
        			return map;
        		}
    			String certificateTextPhoto = multiRequest.getParameter("certificateTextPhoto");
    			String businessTextPhoto = multiRequest.getParameter("businessTextPhoto");
    			certificatePhotoStr=certificateTextPhoto;
				businessPhotoStr=businessTextPhoto;
    			if(StringUtils.isEmpty(certificateTextPhoto)||StringUtils.isEmpty(businessTextPhoto)){
    				//取得request中的所有文件名
        			Iterator<String> iter = multiRequest.getFileNames();
        			//创建ftp链接
        			String ftp_photoDirectory="shop/apply/" + DateUtils.toYmdX(new Date());
        			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
        			while(iter.hasNext()){
        				String name=iter.next();
        				//取得上传文件
        				List<MultipartFile> fileList = multiRequest.getFiles(name);
        				if(fileList!=null){
        					for(MultipartFile file:fileList){
        						if(file != null){
        							//取得当前上传文件的文件名称
        	    					String myFileName = file.getOriginalFilename();
        	    					myFileName=FtpUtil2.generateFileName(myFileName);
        	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
        	    					if(myFileName.trim() !=""){
        	    						myFileName=FtpUtil2.generateFileName(myFileName);
        	    						InputStream is = file.getInputStream();
        	    						FtpUtil2.upload(myFileName, is, ftpClient);
        	    						if(name.equals("certificatePhoto")){
        	    							certificatePhotoStr+=ftp_photoDirectory+"/"+myFileName;
        	    						}else if(name.equals("businessPhoto")){
        	    							businessPhotoStr+=ftp_photoDirectory+"/"+myFileName;
        	    						}
        	    					}
        						}
        					}
        				}
        			}
    			}
    			String merchartClassifyId = multiRequest.getParameter("merchartClassifyId");
    			String merchantAddress = multiRequest.getParameter("merchantAddress");
    			String merchartIntro = multiRequest.getParameter("merchartIntro");
    			String userName = multiRequest.getParameter("userName");
    			String idNo = multiRequest.getParameter("idNo");
    			merchant.setMerchantName(merchantName);
    			merchant.setMerchartClassifyId(Long.parseLong(merchartClassifyId));
    			merchant.setMerchantAddress(merchantAddress);
    			merchant.setMerchartIntro(merchartIntro);
    			merchant.setSchoolId(ud.getSchoolId());
    			merchant.setHandIdcardImg(certificatePhotoStr);
    			merchant.setHardBusinessLicenseImg(businessPhotoStr);  
    			merchant.setState((byte)1);
    			merchantService.updateByPrimaryKeySelective(merchant);
    			Users users=new Users();
    			users.setUserId(ud.getUserId());
    			users.setRealName(userName);
    			users.setIdNo(idNo);
    			users.setMerchantId(merchant.getMerchantId());
    			userService.updateByPrimaryKeySelective(users);
    			map.put("state", 1);
    			map.put("msg", "修改成功");
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "修改失败");
    	}finally {
    		try {
				if(ftpClient!=null){
					FtpUtil2.closeConnection(ftpClient);
				}
			} catch (Exception e) {
				ftpClient=null;
			} 
		}
		return map;
	}
	/**
	 * 店铺修改
	 * @param req
	 * @return
	 */
	@RequestMapping("web/shopUpdate")
	@ResponseBody
	public Map<String, Object> shopUpdate(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        InputStream is = null;
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
        String merchantName = multiRequest.getParameter("merchantName");
        String merchartClassifyId = multiRequest.getParameter("merchartClassifyId");
        String merchantAddress = multiRequest.getParameter("merchantAddress");
        String merchartIntro = multiRequest.getParameter("merchartIntro");

        String merchantHeadImg = multiRequest.getParameter("merchantHeadImg");
        String[] merchantInteriorImg = multiRequest.getParameterValues("merchantInteriorImg");
        try{
     
            mainPhotoStr=merchantHeadImg;
            for(String goodsText:merchantInteriorImg){
                if(!StringUtils.isEmpty(goodsText)){
                    if(StringUtils.isEmpty(photoStr)){
                        photoStr=goodsText;
                    }else{
                        photoStr+=","+goodsText;
                    }
                }
            }
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("merchantHeadImgMain")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        is=file.getInputStream();
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        //按照比例进行缩小和放大
                                        Thumbnails.of(file.getInputStream()).size(120,120).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                    	 myFileName=FtpUtil2.generateFileName(myFileName);
                                         //按照比例进行缩小和放大
                                         is=file.getInputStream();
                                         int len=is.available();
                                         ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                         if(len/1024>600) {//kb
                                         	//按照比例进行缩小和放大
                                             Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                             is = new ByteArrayInputStream(bos.toByteArray());
                                         }
                                        
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                Map<String, Object> paramMap=new HashMap<String, Object>();
    			paramMap.put("merchantName", merchantName);
    			paramMap.put("merchantId", ud.getMerchantId());
    			int count=merchantService.verifyMerchantName(paramMap);
        		if(count>0){
        			map.put("state", 2);
        			map.put("msg", "店铺名称已经存在");
        			return map;
        		}
    			Merchant merchant=new Merchant();
    			merchant.setMerchantId(ud.getMerchantId());
    			merchant.setMerchantName(merchantName);
    			merchant.setMerchartClassifyId(Long.parseLong(merchartClassifyId));
    			merchant.setMerchantAddress(merchantAddress);
    			merchant.setMerchartIntro(merchartIntro);
    			merchant.setSchoolId(ud.getSchoolId());
    			merchant.setMerchantHeadImg(mainPhotoStr);
    			merchant.setMerchantInteriorImg(photoStr);
    			merchantService.updateByPrimaryKeySelective(merchant);
    			map.put("state", 1);
    			map.put("msg", "修改成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }finally {
         	try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
        return map;
		
		
		
		
		
		
		
	}
	
	/**
     * 获取商品图片
     * @param req
     * @return
     */
    @RequestMapping("web/getGoodsPhoto")
    public void getGoodsPhoto(HttpServletRequest req,HttpServletResponse res){
        String photoStr=req.getParameter("photoUrl");
        OutputStream os =null;
        InputStream is =null;
        FTPClient ftpClient =null;
        try {
            res.setContentType("image/jpg");
            ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
            if(photoStr.lastIndexOf("/")>0){
                FtpUtil2.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
                is=FtpUtil2.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
            }else{
                is=FtpUtil2.retrieveFileStream(photoStr, ftpClient);
            }
            os=res.getOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                os.close();
            } catch (IOException e) {
                os=null;
            }
            try {
                is.close();
            } catch (IOException e) {
                is=null;
            }
        }
    }
}
